package com.lap.generator.infrastructure.persistence;

import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.repository.FileRenderer;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;

public class TemplateEngine implements FileRenderer {
  private Configuration cfg;

  public TemplateEngine() throws IOException {
    cfg = new Configuration(Configuration.VERSION_2_3_31);
    cfg.setClassLoaderForTemplateLoading(TemplateEngine.class.getClassLoader(), "templates");
    cfg.setDefaultEncoding("UTF-8");
  }

  public String processTemplate(String templateName, TemplateModel data)
      throws TemplateException, IOException {
    Template template = cfg.getTemplate(templateName);
    StringWriter writer = new StringWriter();
    template.process(data, writer);
    return writer.toString();
  }
}
